package com.xzlf;

import java.awt.*;

public class Bullet {
    private int x, y;
    private static final int SPEED = 20;
    public static final int WIDTH = ResourceMgr.bulletD.getWidth();
    public static final int HEIGHT = ResourceMgr.bulletD.getHeight();
    private Dir dir;
    private Group group;

    Rectangle rectangle;
    private boolean living;

    TankFrame frame;

    public Bullet(int x, int y, Dir dir, boolean living, Group group, TankFrame frame) {
        this.x = x;
        this.y = y;
        this.dir = dir;
        this.living = living;
        this.group = group;
        this.frame = frame;
        rectangle = new Rectangle(x, y, WIDTH, HEIGHT);
    }


    public void paint(Graphics g) {
        if (!living) {
            frame.bullets.remove(this);
            return;
        }
        switch (dir) {
            case UP:
                g.drawImage(ResourceMgr.bulletU, x, y, null);
                break;
            case DOWN:
                g.drawImage(ResourceMgr.bulletD, x, y, null);
                break;
            case LEFT:
                g.drawImage(ResourceMgr.bulletL, x, y, null);
                break;
            case RIGHT:
                g.drawImage(ResourceMgr.bulletR, x, y, null);
                break;
        }
        move();
        rectangle.x = x;
        rectangle.y = y;
    }

    private void move() {
        if (dir == Dir.UP)
            y -= SPEED;
        if (dir == Dir.DOWN)
            y += SPEED;
        if (dir == Dir.LEFT)
            x -= SPEED;
        if (dir == Dir.RIGHT)
            x += SPEED;
        if (x < 0 || y < 0 || x > frame.GAME_WIDTH || y > frame.GAME_HEIGHT) living = false;
    }

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }

    public Dir getDir() {
        return dir;
    }

    public void setDir(Dir dir) {
        this.dir = dir;
    }

    public void colid(Tank tank) {
        if (group == tank.getGroup()) return;
        if (rectangle.intersects(tank.rectangle)) {
            die();
            tank.die();
            int ex = x + Tank.WIDTH / 2 - Explode.WIDTH / 2;
            int ey = y + Tank.HEIGHT / 2 - Explode.HEIGHT / 2;
            frame.explodes.add(new Explode(ex, ey, this.frame));
        }
    }

    public boolean isLiving() {
        return living;
    }

    public void setLiving(boolean living) {
        this.living = living;
    }

    private void die() {
        setLiving(false);
    }

}
